from information.utils.response_code import RET
from . import index_blu
from flask import render_template, request, jsonify, current_app
from .. import data

@index_blu.route('/',methods=['GET'])
def index():
    from information.utils.models import Category
    try:
        #查询所以新闻分类
        category_li=Category.query.all()
        category_lis=[]
        for ca in category_li:
            category_lis.append(ca.to_dict())
        data['category_li']=category_lis
        from information.utils.models import News
        #查询点击排行前6的新闻
        news = News.query.order_by(News.clicks.desc()).limit(6).all()
        news_dict_li_r = []
        for new in news:
            news_dict_li_r.append(new.to_basic_dict())
        data['news_dict_li_r']=news_dict_li_r
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    return render_template('news/index.html',data=data)

@index_blu.route('/news_list',methods=['GET'])
def news_list():
    cid = request.args.get('cid')
    page=request.args.get('page')
    if not all([cid,page]):
        return jsonify(errno=RET.PARAMERR, errmsg='请求参数有误')
    from information.utils.models import News
    try:
        news=News.query.filter_by(category_id=int(cid)).order_by(News.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    news_dict_li=[]
    #动态加载网页，每次加载10条新闻
    for new in news[10*(int(page)-1):10*int(page)]:
        news_dict_li.append(new.to_basic_dict())
    data['total_page']=len(news)//10+1
    data['news_dict_li']=news_dict_li
    return jsonify(errno=RET.OK, errmsg='请求成功',data=data)

@index_blu.route('/error_page',methods=['GET'])
def error_page():
    return render_template('news/404.html',data=data)